import React, { useState, useEffect } from 'react';
import { NavBar, Button, Toast, Modal } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import styles from './CardRecharge.module.css';

function CardRecharge() {
  const navigate = useNavigate();
  const [selectedAmount, setSelectedAmount] = useState(10);
  const [cardInfo, setCardInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [recharging, setRecharging] = useState(false);

  const amounts = [10, 50, 100, 200, 500];

  // 模拟卡片信息
  const mockCardInfo = {
    mealCard: {
      cardNumber: '2024001001234567',
      balance: 200.00
    },
    campusCard: {
      balance: 200.00
    },
    isSynced: true
  };

  // 加载卡片信息
  const loadCardInfo = async () => {
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      setCardInfo(mockCardInfo);
    } catch (error) {
      console.error('获取卡片信息错误:', error);
      Toast.show({ content: '获取信息失败' });
    } finally {
      setLoading(false);
    }
  };

  // 处理充值
  const handleRecharge = () => {
    Modal.confirm({
      content: `确认充值 ¥${selectedAmount} 到饭卡吗？充值后校园卡余额也会同步更新。`,
      onConfirm: async () => {
        setRecharging(true);
        try {
          // 模拟充值过程
          await new Promise(resolve => setTimeout(resolve, 2000));
          
          // 更新余额
          const newBalance = cardInfo.mealCard.balance + selectedAmount;
          setCardInfo({
            ...cardInfo,
            mealCard: {
              ...cardInfo.mealCard,
              balance: newBalance
            },
            campusCard: {
              ...cardInfo.campusCard,
              balance: newBalance
            }
          });
          
          Toast.show({
            content: `充值成功！余额：¥${newBalance.toFixed(2)}`,
            duration: 3000,
          });
          
          // 延迟返回
          setTimeout(() => {
            navigate('/cloud-payment');
          }, 2000);
        } catch (error) {
          console.error('充值错误:', error);
          Toast.show({ content: '充值失败，请重试' });
        } finally {
          setRecharging(false);
        }
      },
    });
  };

  useEffect(() => {
    loadCardInfo();
  }, []);

  if (loading) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate('/cloud-payment')} className={styles.navBar}>
          充值
        </NavBar>
        <div className={styles.content}>
          <div className={styles.loading}>加载中...</div>
        </div>
      </div>
    );
  }

  if (!cardInfo || !cardInfo.mealCard) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate('/cloud-payment')} className={styles.navBar}>
          充值
        </NavBar>
        <div className={styles.content}>
          <div className={styles.errorMessage}>
            <p>未找到饭卡信息，请先绑定校园卡</p>
            <Button color='primary' onClick={() => navigate('/campus-card-bind')}>
              去绑定
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <NavBar onBack={() => navigate('/cloud-payment')} className={styles.navBar}>
        饭卡充值
      </NavBar>
      
      <div className={styles.content}>
        <div className={styles.cardInfo}>
          <h2 className={styles.cardNumber}>卡号 {cardInfo.mealCard.cardNumber}</h2>
          <div className={styles.balanceInfo}>
            <div className={styles.balanceRow}>
              <span className={styles.balanceLabel}>饭卡余额</span>
              <span className={styles.balanceAmount}>¥{cardInfo.mealCard.balance.toFixed(2)}</span>
            </div>
            <div className={styles.balanceRow}>
              <span className={styles.balanceLabel}>校园卡余额</span>
              <span className={styles.balanceAmount}>¥{cardInfo.campusCard.balance.toFixed(2)}</span>
            </div>
            <div className={styles.syncStatus}>
              {cardInfo.isSynced ? (
                <span className={styles.synced}>✅ 余额已同步</span>
              ) : (
                <span className={styles.notSynced}>⚠️ 余额未同步</span>
              )}
            </div>
          </div>
        </div>

        <div className={styles.amountSection}>
          <h3 className={styles.sectionTitle}>请选择充值金额</h3>
          <div className={styles.amountGrid}>
            {amounts.map(amount => (
              <button
                key={amount}
                className={`${styles.amountButton} ${
                  selectedAmount === amount ? styles.selected : ''
                }`}
                onClick={() => setSelectedAmount(amount)}
              >
                ¥{amount}
              </button>
            ))}
          </div>
        </div>

        <div className={styles.paymentSection}>
          <h3 className={styles.sectionTitle}>支付方式</h3>
          <div className={styles.paymentMethod}>
            <span className={styles.paymentIcon}>💳</span>
            <span className={styles.paymentText}>云缴费在线支付</span>
          </div>
        </div>

        <div className={styles.notice}>
          <h4>充值说明：</h4>
          <ul>
            <li>充值成功后，饭卡和校园卡余额将自动同步</li>
            <li>充值金额实时到账，可立即使用</li>
            <li>支持微信、支付宝等多种支付方式</li>
            <li>如有问题，请联系客服</li>
          </ul>
        </div>

        <Button
          block
          color='primary'
          size='large'
          className={styles.rechargeButton}
          onClick={handleRecharge}
          loading={recharging}
        >
          {recharging ? '充值中...' : `确认充值 ¥${selectedAmount}`}
        </Button>
      </div>
    </div>
  );
}

export default CardRecharge;